import axios from 'axios'
import qs from 'qs'
//import { log } from './index'
import { MessageBox, Message } from 'element-ui'
import HOST from './host.js'
//console.log(HOST)
export default {
  install(Vue, { router, store, needAuth = false }) {
    axios.defaults.baseURL = HOST

    // request interceptor
    axios.interceptors.request.use(
      config => {
        config.headers = {
          ...config.headers,
          authorization:localStorage.getItem('authorization')
        }
        return config
      },
      error => {
        Message({
            message: 'timed out!',
            type: 'error',
            duration: 5 * 1000
          })
        return Promise.reject(error)
      }
    )

    // response interceptorinterceptor
    axios.interceptors.response.use(
      response => {
        const { authorization } = response.headers
        //let authorization = response.headers['Authorization']
        //console.log(response.headers)
        //登陆状态校验，有则重置当前token
        if (authorization) {
          //store.commit('admin/updateToken', authorization)
          localStorage.setItem('authorization',authorization)
        }
        return response.data?response.data:{}
      },
      err => {
        if (!err.response) {
          Message({
            message: err,
            type: 'error',
            duration: 5 * 1000
          })
          return Promise.reject(err)
        }

        const status = err.response.status
        const message = err.response.data.message
        if (process.env.NODE_ENV === 'development') {
          console.log('error: ' + message)
        }
        if (status === 401) {
          Message({
            message: "登陆超时，请重新登陆",
            type: 'error',
            duration: 3 * 1000
          })
          setTimeout(() => {
            router.push(`/login`)
          }, 3000);
          //this.$router.push(`/login?redirect=${this.$route.fullPath}`)
        }else if(status === 400){
          Message({
            message: err.response.data.msg,
            type: 'error',
            duration: 5 * 1000
          })
        } else {
          Message({
            message: message || '发生错误，请刷新重试！',
            type: 'error',
            duration: 5 * 1000
          })
        }
        return Promise.reject(err)
      }
    )

    const getHeader = () => {
      return needAuth
        ? {
          //Authorization: `Bearer ${store.getters.token}`
          authorization:localStorage.getItem('authorization')
        }
        : {}
    }

    // request methods

    /**
     *
     * @param {*} url
     * @param {*} data
     */
    const get = (url, data = {}) => {
      return axios({
        method: 'get',
        url,
        params: data
      })
    }

    /**
     *
     * @param {*} url
     * @param {*} data
     */
    const post = (url, data = {}) => {
      data = qs.stringify(data)
      return axios({
        method: 'post',
        url,
        data
      })
    }

    /**
     *
     * @param {*} url
     * @param {*} data
     */
    const put = (url, data = {}) => {
      //data = qs.stringify(data)
      return axios({
        method: 'put',
        url,
        data,
        // headers: {
        //   ''Content-Type': 'application/x-www-form-urlencoded'
        // }
      })
    }

    /**
     *
     * @param {*} url
     * @param {*} data
     */
    const del = (url, data = {}) => {
      url = url + '/' + data.id
      return axios({
        method: 'delete',
        url
      })
    }

    /**
     *
     * @param {*} url
     * @param {*} data
     */
    const upload = (url, data = {}) => {
      return axios({
        method: 'post',
        url,
        data,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
    }

    const download = (url, data = {}) => {
      return axios({
        method: 'get',
        url,
        responseType: 'blob',
        params: data
      })
    }

    /**
     * all methods
     */
    const methods = {
      get,
      post,
      put,
      delete: del,
      upload,
    }

    /**
     * package function
     */
    const ax = {}

    Object.keys(methods).forEach(key => {
      ax[key] = methods[key]
    })

    Vue.prototype.$axios = ax
  }
}
